package com.supreme.threadserver.service;

import com.supreme.common.constant.ConsoleColors;
import com.supreme.commontools.SleepUtils;
import org.springframework.stereotype.Service;

@Service
public class ThreadService {

    private final Object syncLock = new Object();

    public void lockMethod() {
        synchronized (syncLock) {
            String threadName = Thread.currentThread().getName();
            ConsoleColors.println(ConsoleColors.GREEN_BOLD_BRIGHT, "Start threadName = " + threadName);
            SleepUtils.sleep(10);
            ConsoleColors.println(ConsoleColors.RED_BOLD_BRIGHT, "Finish threadName = " + threadName);
        }
    }

    public void waitMethod() {
        synchronized (syncLock) {
            String threadName = Thread.currentThread().getName();
            ConsoleColors.println(ConsoleColors.GREEN_BOLD_BRIGHT, "Start threadName = " + threadName);
            try {
                syncLock.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            ConsoleColors.println(ConsoleColors.RED_BOLD_BRIGHT, "Finish threadName = " + threadName);
        }
    }

    public void notifyMethod() {
        synchronized (syncLock) {
            syncLock.notify();
        }
    }

    public void notifyAllMethod() {
        synchronized (syncLock) {
            syncLock.notifyAll();
        }
    }
}
